package cn.jee.controller;

import cn.jee.entity.Order;
import cn.jee.entity.Product;
import cn.jee.entity.User;
import cn.jee.repository.OrderRepository;
import cn.jee.repository.ProductRepository;
import cn.jee.repository.UserRepository;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

// 文件名：OrderController.java
@Controller
public class OrderController {

  @Autowired
  private UserRepository userRepository;
  @Autowired
  private OrderRepository orderRepository;

//  @GetMapping("/purchased")
//  public String viewPurchasedProducts(@RequestParam("username") String username, Model model) {
//    User user = userRepository.findByUsername(username);
//    List<Order> orders = orderRepository.findByUserAndSubmittedTrue(user);
//
//    List<Product> allPurchasedProducts = new ArrayList<>();
//    for (Order order : orders) {
//      allPurchasedProducts.addAll(order.getProducts());
//    }
//
//    model.addAttribute("products", allPurchasedProducts);
//    return "purchased";
//  }
//
//  // 文件名：OrderController.java（继续添加）
//  @GetMapping("/orders")
//  public String viewOrders(@RequestParam("username") String username, Model model) {
//    User user = userRepository.findByUsername(username);
//    List<Order> orders = orderRepository.findByUserAndSubmittedTrue(user);
//
//    model.addAttribute("orders", orders);
//    return "order_list";
//  }
@GetMapping("/orders")
public String viewOrders(@RequestParam("username") String username,
                         Model model,
                         HttpSession session) {
  User user = userRepository.findByUsername(username);
  session.setAttribute("user", user); // 确保session中有user
  model.addAttribute("user", user); // 确保model中有user

  List<Order> orders = orderRepository.findByUserAndSubmittedTrue(user);
  model.addAttribute("orders", orders);
  return "order_list";
}

  @GetMapping("/purchased")
  public String viewPurchasedProducts(@RequestParam("username") String username,
                                      Model model,
                                      HttpSession session) {
    User user = userRepository.findByUsername(username);
    session.setAttribute("user", user); // 确保session中有user
    model.addAttribute("user", user); // 确保model中有user

    List<Order> orders = orderRepository.findByUserAndSubmittedTrue(user);
    List<Product> allPurchasedProducts = new ArrayList<>();

    for (Order order : orders) {
      allPurchasedProducts.addAll(order.getProducts());
    }

    model.addAttribute("products", allPurchasedProducts);
    return "purchased";
  }
}
